/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.tcc;

import com.inspur.edp.bef.core.session.FuncSession;
import com.inspur.edp.bef.core.session.FuncSessionManager;
import com.inspur.edp.caf.transaction.api.annoation.tcc.BusinessActionContext;
import io.iec.edp.caf.common.JSONSerializer;
import java.util.Objects;
import org.springframework.util.StringUtils;

public class TccUtil {

  //region put/get BefTccParam
  private static final String paramKey_Value = "BefTccValue";
  private static final String paramKey_Sessionid = "BefTccSessionId";

  public static BefTccParam getTccParam(BusinessActionContext context){
    Objects.requireNonNull(context);

    String sessionId = context.getParameter(paramKey_Sessionid, String.class);
    if(StringUtils.isEmpty(sessionId))
      return null;

    FuncSession session = FuncSessionManager.getCurrent().getSession(sessionId);
    BefTccParam rez = session != null ? session.getTccParam(context.getLogId()) : null;
    if(rez == null) {
      String value = context.getParameter(paramKey_Value, String.class);
      rez = JSONSerializer.deserialize(value, BefTccParam.class);
//      for(BefTccParamItem item : rez.getItems()) {
//        if (StringUtils.isEmpty(item.getChangesStr())) {
//          System.out.println("[BefTcc]二阶段[" + context.getLogId() + "]参数结构不完整:");
//          System.out.println(value);
//        }
//      }
      rez.setSessionId(sessionId);
    }
    return rez;
  }

  public static void putTccParam(BusinessActionContext context, BefTccParam param) {
    context.putParameter(paramKey_Sessionid, param.getSessionId());
    String befTccParamStr = JSONSerializer.serialize(param);
//    System.out.println("[BefTcc]一阶段[" + context.getLogId() + "]注册参数:");
//    System.out.println(befTccParamStr);
    context.putParameter(paramKey_Value, befTccParamStr);
  }
  //endregion
}
